package org.jeecg.modules.drive.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DynamicDataSourceModel;
import org.jeecg.modules.device.service.IDevDeviceRecordService;
import org.jeecg.modules.drive.entity.DevDriveModel;
import org.jeecg.modules.drive.service.DriveCommonDbService;
import org.jeecg.modules.drive.service.IDevDriveModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

 /**
 * @Description: 租户设备驱动模型
 * @Author: jeecg-boot
 * @Date:   2024-04-16
 * @Version: V1.0
 */
@Api(tags="租户设备驱动模型")
@RestController
@RequestMapping("/drive/devDriveModel")
@Slf4j
public class DevDriveModelController extends JeecgController<DevDriveModel, IDevDriveModelService> {
	@Autowired
	private IDevDriveModelService devDriveModelService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private DriveCommonDbService driveCommonService;
	@Autowired
	private IDevDeviceRecordService deviceRecordService;
	
	/**
	 * 分页列表查询
	 *
	 * @param devDriveModel
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "租户设备驱动模型-分页列表查询")
	@ApiOperation(value="租户设备驱动模型-分页列表查询", notes="租户设备驱动模型-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DevDriveModel>> queryPageList(DevDriveModel devDriveModel,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<DevDriveModel> queryWrapper = QueryGenerator.initQueryWrapper(devDriveModel, req.getParameterMap());
		Page<DevDriveModel> page = new Page<DevDriveModel>(pageNo, pageSize);
		IPage<DevDriveModel> pageList = devDriveModelService.page(page, queryWrapper);

		//List<Map> deviceType（设备类型），driveReadData（设备数据值），deviceUnit(设备单位)，uniqueId（设备唯一键值）
		// List<Map<String, Object>> maps = driveCommonService.readDeviceDataByDb("4028810c6aed99e1016aed9b31b40002");
		// if(null != maps && maps.size()>0){
		// 	for (Map<String, Object> map : maps) {
		// 		String deviceType = map.get("deviceType").toString();
		// 		String driveReadData =map.get("driveReadData").toString();
		// 		String deviceUnit = (String) map.get("deviceUnit");
		// 		String uniqueId = (String) map.get("uniqueId");
		// 		DevDeviceRecord deviceRecord = new DevDeviceRecord();
		// 		deviceRecord.setDeviceType(deviceType);
		// 		deviceRecord.setDeviceCode(uniqueId);
		// 		deviceRecord.setDeviceValue(driveReadData);
		// 		deviceRecord.setDeviceUnit(deviceUnit);
		// 		deviceRecordService.save(deviceRecord);
		// 	}
		// }


		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param devDriveModel
	 * @return
	 */
	@AutoLog(value = "租户设备驱动模型-添加")
	@ApiOperation(value="租户设备驱动模型-添加", notes="租户设备驱动模型-添加")
	@RequiresPermissions("drive:iot_dev_drive_model:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DevDriveModel devDriveModel) {
		boolean save = devDriveModelService.save(devDriveModel);
		if(save && "1".equals(devDriveModel.getDriveType())){//库表模式才创建动态数据源
			//保存动态数据源
			DynamicDataSourceModel dataSource =new DynamicDataSourceModel();
			dataSource.setDbPassword(devDriveModel.getDrivePassword());
			dataSource.setDbUsername(devDriveModel.getDriveUsername());
			dataSource.setDbType(devDriveModel.getDatabaseType());
			String databaseType = devDriveModel.getDatabaseType();
			if(databaseType.equals("1") || databaseType.equals("4")){
				databaseType="mysql";

				String url="jdbc:mysql://"+devDriveModel.getDriveIp()+":"+devDriveModel.getDrivePort()
						+"/"+devDriveModel.getDriveDatabases()+ "?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
				dataSource.setDbUrl(url);
				dataSource.setDbDriver("com.mysql.cj.jdbc.Driver");
			}else{
				//
				throw new JeecgBootException("暂只支持mysql数据库");
			}
			String ddsId = sysBaseAPI.saveDynamicDbSource(dataSource);
			if(StringUtils.isNotEmpty(ddsId)){
				devDriveModelService.update(Wrappers.<DevDriveModel>lambdaUpdate()
						.set(DevDriveModel::getDataSourceId,ddsId)
						.eq(DevDriveModel::getId,devDriveModel.getId()));
			}
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param devDriveModel
	 * @return
	 */
	@AutoLog(value = "租户设备驱动模型-编辑")
	@ApiOperation(value="租户设备驱动模型-编辑", notes="租户设备驱动模型-编辑")
	@RequiresPermissions("drive:iot_dev_drive_model:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DevDriveModel devDriveModel) {
		boolean save = devDriveModelService.updateById(devDriveModel);
		if(save && "1".equals(devDriveModel.getDriveType())){//库表模式才创建动态数据源
			//保存动态数据源
			DynamicDataSourceModel dataSource =new DynamicDataSourceModel();
			dataSource.setDbPassword(devDriveModel.getDrivePassword());
			dataSource.setDbUsername(devDriveModel.getDriveUsername());
			dataSource.setDbType(devDriveModel.getDatabaseType());
			dataSource.setName(devDriveModel.getDriveAlias());
			dataSource.setId(devDriveModel.getDataSourceId());
			/**
			 * MySQL5.5		1
			 * MYSQL5.7+	4
			 * Oracle		2
			 * SQLServer	3
			 * postgresql	6
			 * marialDB		5
			 * 达梦		7
			 * 人大金仓	8
			 * 神通		9
			 * SQLite	10
			 */
			String databaseType = devDriveModel.getDatabaseType();
			if(databaseType.equals("1") || databaseType.equals("4")){
				databaseType="mysql";

				String url="jdbc:mysql://"+devDriveModel.getDriveIp()+":"+devDriveModel.getDrivePort()
						+"/"+devDriveModel.getDriveDatabases()+ "?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
				dataSource.setDbUrl(url);
				dataSource.setDbDriver("com.mysql.cj.jdbc.Driver");
			}else{
				//
				throw new JeecgBootException("暂只支持mysql数据库");
			}
			String ddsId = sysBaseAPI.saveDynamicDbSource(dataSource);
			if(StringUtils.isNotEmpty(ddsId)){
				devDriveModelService.update(Wrappers.<DevDriveModel>lambdaUpdate()
						.set(DevDriveModel::getDataSourceId,ddsId)
						.eq(DevDriveModel::getId,devDriveModel.getId()));
			}
		}
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "租户设备驱动模型-通过id删除")
	@ApiOperation(value="租户设备驱动模型-通过id删除", notes="租户设备驱动模型-通过id删除")
	@RequiresPermissions("drive:iot_dev_drive_model:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		devDriveModelService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "租户设备驱动模型-批量删除")
	@ApiOperation(value="租户设备驱动模型-批量删除", notes="租户设备驱动模型-批量删除")
	@RequiresPermissions("drive:iot_dev_drive_model:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.devDriveModelService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "租户设备驱动模型-通过id查询")
	@ApiOperation(value="租户设备驱动模型-通过id查询", notes="租户设备驱动模型-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DevDriveModel> queryById(@RequestParam(name="id",required=true) String id) {
		DevDriveModel devDriveModel = devDriveModelService.getById(id);
		if(devDriveModel==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(devDriveModel);
	}

	/**
     * 批量启用
     */
    @AutoLog(value = "租户设备驱动模型-批量启用")
    //@ApiOperation(value="租户设备驱动模型-批量启用", notes="租户设备驱动模型-批量启用")
    //@RequiresPermissions("devDriveModel:batchEnable")
    @DeleteMapping(value = "/formEnable")
    public Result<?> batchFormEnable(@RequestParam(name="ids",required=true) String ids) {
        this.devDriveModelService.batchFormEnable(ids);
        return Result.ok("启用成功");
    }
    /**
     * 批量禁用
     */
    @AutoLog(value = "租户设备驱动模型-批量禁用")
    //@ApiOperation(value="租户设备驱动模型-批量禁用", notes="租户设备驱动模型-批量禁用")
    //@RequiresPermissions("devDriveModel:batchDisable")
    @DeleteMapping(value = "/formDisable")
    public Result<?> batchFormDisable(@RequestParam(name="ids",required=true) String ids) {
        this.devDriveModelService.batchFormDisable(ids);
        return Result.ok("禁用成功");
    }

    /**
    * 导出excel
    *
    * @param request
    * @param devDriveModel
    */
    @RequiresPermissions("drive:iot_dev_drive_model:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DevDriveModel devDriveModel) {
        return super.exportXls(request, devDriveModel, DevDriveModel.class, "租户设备驱动模型");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("drive:iot_dev_drive_model:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DevDriveModel.class);
    }

}
